<template>
  <div>
    <!-- alert 警示框 -->
    <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
    <!-- steps 步骤条 -->
    <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- form 表单 -->
    <el-form :model="goods.addGoodsParams" :rules="addFormRules" ref="addFormRef" label-position="top">
      <!-- tabs 标签页 -->
      <el-tabs type="border-card" tab-position="left" v-model="activeIndex" :before-leave="beforeTableave"
        style="height: 100%">
        <el-tab-pane label="基本信息" name="0">

          <!-- form 表单验证项 -->
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="goods.addGoodsParams.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="goods.addGoodsParams.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="goods.addGoodsParams.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="goods.addGoodsParams.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <!-- Cascader 级联选择器 -->
            <el-cascader v-model="goods.addGoodsParams.goods_cat" :options="goods.categoryList" :props="{
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
              children: 'children'
            }" @change="cascaderHandleChange" style="width: 100%;"></el-cascader>
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">

          <!-- form 表单验证项 -->
          <el-form-item v-for="item in goods.manyAttributeList" :key='item.attr_id' :label="item.attr_name">
            <!-- Checkbox 多选框 -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox v-for="(checkbox, index) in item.attr_vals" :key="index" :label="checkbox" border />
            </el-checkbox-group>
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">

          <!-- form 表单验证项 -->
          <el-form-item v-for="item in goods.onlyAttributeList" :key='item.attr_id' :label="item.attr_name">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">

          <!-- Upload 上传 -->
          <el-upload :action="goods.uploadUrl" list-type="picture-card" drag :headers="headerObj" method="post"
            :on-preview="handlePreview" :on-remove="handleRemove" :on-success="uploadSuccees">
            <!-- 图标 -->
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <!-- 文本 -->
            <div class="el-upload__text">
              将文件拖放到此处或<em>点击上传</em>
            </div>
          </el-upload>

          <!-- dialog 图片预览 -->
          <el-dialog v-model="dialogVisible" width="80%">
            <template #header>图片预览</template>
            <img w-full :src="dialogImageUrl" alt="Preview Image" style="width:100%;" />
          </el-dialog>

        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">

          <!-- 富文本编辑器组件 -->
          <MdEditor v-model="goods.addGoodsParams.goods_introduce"></MdEditor>

        </el-tab-pane>
        <el-tab-pane label="确认提交" name="5">

          <el-button type="primary" plain @click="addGoods">确认提交</el-button>

        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script setup>
import MdEditor from 'md-editor-v3';//富文本编辑器组件
import 'md-editor-v3/lib/style.css';//富文本编辑器组件
import { ref } from "vue"
import { useRouter } from 'vue-router';
import useStore from "@/pinia/index.js";
import { ElMessage, ElNotification, ElMessageBox } from "element-plus"; //消息提示框
const { goods } = useStore();
const router = useRouter();
// 请求商品分类数据列表
goods.REQUEST_categoryList();
// 默认激活项
const activeIndex = ref(0)
// 表单验证对象
const addFormRef = ref()
// 表单验证规则
const addFormRules = {
  goods_name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  goods_cat: [
    { required: true, message: "请选择商品分类", trigger: "blur" }
  ],
  goods_price: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
    { min: 0, max: 1000000, message: "长度在 0 到 1000000 个字符", trigger: "blur" }
  ],
  goods_number: [
    { required: true, message: "请输入商品库存", trigger: "blur" },
    { min: 0, max: 1000000, message: "长度在 0 到 1000000 个字符", trigger: "blur" }
  ],
  goods_weight: [
    { required: true, message: "请输入商品重量", trigger: "blur" },
    { min: 0, max: 1000000, message: "长度在 0 到 1000000 个字符", trigger: "blur" }
  ]
}
// 级联选择器change事件
const cascaderHandleChange = () => {
  if (goods.addGoodsParams.goods_cat.length !== 3) {
    ElMessage.error('请选择三级商品分类！')
    goods.addGoodsParams.goods_cat = []//选中的不是三级分类，清空数据
  } else {
    goods.attributeParams.id = goods.addGoodsParams.goods_cat[2]; // 拿到三级分类id，放到属性参数中
    goods.attributeParams1.id = goods.addGoodsParams.goods_cat[2]; // 拿到三级分类id，放到属性参数中
    goods.REQUEST_onlyAttributeList(); // 请求商品静态属性列表
    goods.REQUEST_manyAttributeList(); // 请求商品动态参数列表
  }
}
// 切换标签页的事件
const beforeTableave = (activeName, oldActiveName) => {
  if (oldActiveName === '0' && goods.addGoodsParams.goods_cat.length === 0) {
    ElMessage.warning('请先选择商品分类！')
    return false
  }
  if (activeName === '1') {
    console.log('商品参数');
  }
  if (activeName === '2') {
    console.log('商品属性');
  }
  if (activeName === '3') {
    console.log('商品图片');
  }
  if (activeName === '4') {
    console.log('商品内容');
  }
  if (activeName === '5') {
    console.log('确认提交');
  }
}
// upload 上传请求头配置携带token
const headerObj = { Authorization: window.sessionStorage.getItem('token') }
// 图片预览的图片路径
const dialogImageUrl = ref('')
// 图片预览弹出框
const dialogVisible = ref(false)
// 图片预览事件 (file:图片对象)
const handlePreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
// 图片上传成功事件 (res：上传成功后的返回值)
const uploadSuccees = (res) => {
  // 定义一个对象并push到数组中
  const obj = { pic: res.data.tmp_path }
  goods.addGoodsParams.pics.push(obj)
}
// 图片移除事件 (file:图片对象)
const handleRemove = (file) => {
  // 1.获取将要删除的图片的临时路径
  const filePath = file.response.data.tem_path
  // 2.从 pics 数组中,找到这个图片的索引值
  const index = goods.addGoodsParams.pics.findIndex((item) => { item.tem_path === filePath })
  // 3.调用数组的 splic 方法,将这个图片从数组中删除
  goods.addGoodsParams.pics.splice(index, 1)
}
// 确认提交按钮的事件
const addGoods = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      // 先清空attrs数组
      goods.addGoodsParams.attrs = []
      // 静态属性
      goods.onlyAttributeList.forEach(item => {
        const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals }
        goods.addGoodsParams.attrs.push(newInfo)
      })
      // 动态参数
      goods.manyAttributeList.forEach(item => {
        const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals.join(',') }
        goods.addGoodsParams.attrs.push(newInfo)
      })
      // 发送请求
      goods.REQUEST_addGoods().then(res => {
        if (res.data.meta.status === 201) {
          activeIndex.value = 6 // 跳到最后一步完成
          // 1s倒计时后路由跳转到商品列表页面
          setTimeout(() => {
            router.push({ path: '/goods/goods' })
          }, 1000)
        }
      })
      // 查看提交项
      // console.log(goods.addGoodsParams.attrs);
    } else {
      ElMessage.error('请完善商品信息！')
      return false
    }
  });
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 10px;
}

.el-steps {
  margin: 20px 0px;
}
</style>

<style>
.el-upload-dragger {
  padding: 10px;
  width: 100%;
  height: 100%;
}
</style>